<?php

namespace Admin\Model;

use Think\Model\RelationModel;

class ArticleModel extends RelationModel {

    protected $trueTableName = 'article';
    protected $_validate = [
        ['title', 'require', '标题不能为空'],
        ['writer', 'require', '作者不能为空'],
        ['is_top', 'number', '排序必须为数字'],
    ];

//    protected $_link = [
//        'Sort' => [
//            'mapping_type' => HAS_ONE,
//            'foreign_key' => 's_id',
//        ],
//    ];

    /**
     * 显示文章列表
     * 分页  排序
     * @param type $where
     * @return type array
     */
    public function getList($param) {
        $article = D('article');
        if (!empty($param['title'])) {
            $where = 'a.title like "%' . $param['title'] . '%"';
        }
//        $query = $article->alias("a")
//                ->field(['a.*', 's.class'])
//                ->where($where)
//                ->join('sort as s on a.s_id=s.id')
//                ->order('a.is_top desc');

        $count = $article->alias("a")
                ->field(['a.*', 's.class'])
                ->where($where)
                ->join('sort as s on a.s_id=s.id')
                ->order('a.is_top desc')
                ->count();
//        $Page = new \Think\Page($count, $param['iDisplayLength']);
        $list = $article->alias("a")
                ->field(['a.*', 's.class'])
                ->where($where)
                ->join('sort as s on a.s_id=s.id')
                ->order('a.is_top desc')
                ->limit($param['iDisplayStart'] . ',' . $param['iDisplayLength'])
                ->select();
//        var_dump($article->getLastSql());die;
        $data = ['list' => $list, 'count' => $count];
        return $data;
    }

    /**
     * 修改 顶置信息  
     * @param type $condition
     * @return boolean
     */
    public function upDateByIsTop($condition) {
        $article = D('article');
        if (empty($condition['id'])) {
            return false;
        }
        $data['is_top'] = intval($condition['is_top']);
        $result = $article->where('id=' . $condition['id'])->save($data);

        if ($result) {
            return true;
        }else{
            return false;

        }
    }

    /**
     * 查看文章详情
     * @param type $id
     */
    public function ArticleInfo($id) {
        $article = D('article');
        $data = $article->field('content')->where('id=' . $id)->select();
        return $data;
    }

}
